<?php

/**
 * @Author: chenjianghui
 * @Date:   2018-07-04 10:26:09
 * @Last Modified by:   chenjianghui
 * @Last Modified time: 2018-08-08 09:50:08
 */

namespace app\common\third;

class WechatModel
{
    const server_url = 'https://api.weixin.qq.com';

    /*
     * 获取微信用户信息
     * @params $access_token
     * @params $openid
     * */
    public static function getUserInfo($access_token, $openid)
    {
        $params = [
            'access_token' => $access_token,
            'openid'       => $openid,
            'lang'         => 'zh_CN',
        ];
        $paramsStr = self::pararmsToStr($params);

        $route  = '/sns/userinfo?';
        $url    = self::server_url . $route . $paramsStr;
        $result = curl($url);
        $result = json_decode($result, true);
        if ($result['errcode']) {
            renderJson('授权失败', 0);
            renderJson($result['errmsg'], $result['errcode']);
        }
        return $result;

    }

    /*
     * 将请求参数数组转换字符串
     * */
    public static function pararmsToStr($pararms)
    {
        $result = '';
        foreach ($pararms as $key => $vo) {
            $result .= "$key=" . $vo . "&";
        }
        $result = substr($result, 0, -1);
        return $result;
    }
}
